package com.pangda.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pangda.common.domain.PageResult;
import com.pangda.common.domain.ResponseResult;
import com.pangda.common.utils.FileUtil;
import com.pangda.common.utils.UserContext;
import com.pangda.pojo.*;
import com.pangda.pojo.data.ClueData;
import com.pangda.pojo.data.SysRoleData;
import com.pangda.pojo.dto.*;
import com.pangda.pojo.vo.BusinessVo;
import com.pangda.pojo.vo.ClueReportVo;
import com.pangda.pojo.vo.ClueVo;
import com.pangda.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 线索表 前端控制器
 * </p>
 *
 * @author author
 * @since 2024-06-21
 */
@RestController
@RequestMapping("/clues")
@Api(tags = "线索管理")
public class ClueController {

    @Autowired
    private IClueService clueService;


    @Autowired
    private IClueReportService clueReportService;


    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IBusinessService businessService;
    @Autowired
    private IActivityService activityService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 添加线索
     *
     * @param dto
     * @return
     */
    @PostMapping("/clue")
    @ApiOperation("添加线索")
    public ResponseResult add(@RequestBody ClueDto dto) {
        dto.setAssignBy(UserContext.getUser());
        dto.setOwner(UserContext.getUser());
        dto.setUserId(dto.getUserId());
        dto.setCreateBy(UserContext.getUser());
        dto.setCreateTime(LocalDateTime.now());
        dto.setStatus("1");
        Clue clue = BeanUtil.toBean(dto, Clue.class);
        String activityId = dto.getActivityId();
        Activity activity = activityService.getById(activityId);
        clue.setActivityInfo(activity.getInfo());
        return ResponseResult.success(clueService.save(clue));
    }

    @ApiOperation("分配线索")
    @PutMapping("/clue/assignment")
    public ResponseResult assignment(@RequestBody AssignDto assign) {
        Integer userId = assign.getUserId();
        int count = clueService.count(new LambdaQueryWrapper<Clue>().eq(Clue::getOwner, userId));
        if (count > 20) {
            return ResponseResult.error("该用户已达到线索最大分配额度20条");
        }
        List<Clue> clues = clueService.listByIds(Arrays.asList(assign.getIds()));
        SysUser user = sysUserService.getById(assign.getUserId());
        clues.stream().forEach(clue -> clue.setOwner(user.getUserName()));
        clueService.updateBatchById(clues);
        return ResponseResult.success();
    }


    @ApiOperation("踢回线索池")
    @PutMapping("/clue/false/{id}")
    public ResponseResult isFalse(@PathVariable Integer id) {
        Clue clue = clueService.getById(id);
        clue.setFalseCount(clue.getFalseCount() + 1);
        clue.setStatus("4");
        clue.setUpdateTime(LocalDateTime.now());
        //如果踢回线索池次数为三次 直接删除该线索
        if (clue.getFalseCount().equals(3)) {
            clueService.removeById(id);
        }
        return ResponseResult.success(clueService.updateById(clue));
    }

    @ApiOperation("线索转商机")
    @PutMapping("/clue/changeBusiness/{id}")
    public ResponseResult changeBusiness(@PathVariable Integer id) {
        Clue clue = clueService.getById(id);
        clue.setStatus("6");
        clue.setUpdateTime(LocalDateTime.now());
        clueService.updateById(clue);
        Business business = BeanUtil.copyProperties(clue, Business.class);
        business.setClueId(clue.getId());
        business.setStatus("1");
        businessService.save(business);
        return ResponseResult.success();
    }

    @ApiOperation("线索捞取")
    @PutMapping("/clue/gain")
    public ResponseResult gain(@RequestBody AssignDto assign) {
        Integer[] ids = assign.getIds();
        List<Clue> clues = clueService.listByIds(Arrays.asList(ids));
        clues.stream().forEach(clue -> {
            clue.setOwner(UserContext.getUser());
            clue.setOwnerTime(LocalDateTime.now());
            clue.setStatus("1");
            clue.setNextTime(null);
        });
        return ResponseResult.success(clueService.updateBatchById(clues));
    }

    @ApiOperation("线索跟进")
    @PostMapping("/record")
    public ResponseResult record(@RequestBody ClueReportDto dto) {
        clueService.addRecored(dto);
        return ResponseResult.success();
    }

    @ApiOperation("线索跟进记录列表查询")
    @GetMapping("/record/list")
    public PageResult recordList(@RequestParam("clueId") Integer clueId) {
        LambdaQueryWrapper<ClueReport> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ClueReport::getClueId, clueId);
        List<ClueReport> list = clueReportService.list(wrapper);
        List<ClueReportVo> clueReportVos = BeanUtil.copyToList(list, ClueReportVo.class);
        return PageResult.success(clueReportVos, ClueReportVo.class);
    }


    @ApiOperation("线索分页查询")
    @GetMapping("/clue/list")
    public PageResult list(CluePageParam param) {
        LambdaQueryWrapper<Clue> wrapper = new LambdaQueryWrapper<>();
        wrapper.ne(Clue::getStatus, 4);
        wrapper.ne(Clue::getStatus, 5);
        wrapper.ne(Clue::getStatus, 6);
        wrapper.like(ObjectUtil.isNotEmpty(param.getId()), Clue::getId, param.getId());
        wrapper.like(ObjectUtil.isNotEmpty(param.getPhone()), Clue::getPhone, param.getPhone());
        wrapper.like(ObjectUtil.isNotEmpty(param.getOwner()), Clue::getOwner, param.getOwner());
        wrapper.eq(ObjectUtil.isNotEmpty(param.getStatus()), Clue::getStatus, param.getStatus());
        wrapper.eq(ObjectUtil.isNotEmpty(param.getChannel()), Clue::getChannel, param.getChannel());
        Map<String, Object> params = param.getParams();
        if (ObjectUtil.isNotEmpty(params.get("beginCreateTime")) && ObjectUtil.isNotEmpty(params.get("endCreateTime"))) {
            wrapper.between(Clue::getCreateTime, params.get("beginCreateTime"), params.get("endCreateTime"));
        }
        Page page = clueService.page(new Page<>(param.getPageNum(), param.getPageSize()), wrapper);
        return PageResult.success(page, Clue.class);
    }


    @ApiOperation("线索详情")
    @GetMapping("/clue/{id}")
    public ResponseResult getInfo(@PathVariable Integer id) {
        return ResponseResult.success(clueService.getById(id));
    }

    @ApiOperation("线索池分页查询")
    @GetMapping("/clue/pool")
    public PageResult cluePoolPage(CluePageParam param) {
        LambdaQueryWrapper<Clue> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Clue::getStatus, 4);
        wrapper.eq(ObjectUtil.isNotEmpty(param.getId()), Clue::getId, param.getId());
        wrapper.eq(ObjectUtil.isNotEmpty(param.getPhone()), Clue::getPhone, param.getPhone());
        wrapper.eq(ObjectUtil.isNotEmpty(param.getChannel()), Clue::getChannel, param.getChannel());
        Map<String, Object> params = param.getParams();
        if (ObjectUtil.isNotEmpty(params.get("beginCreateTime")) && ObjectUtil.isNotEmpty(params.get("endCreateTime"))) {
            wrapper.between(Clue::getCreateTime, params.get("beginCreateTime"), params.get("endCreateTime"));
        }
        Page page = clueService.page(new Page<>(param.getPageNum(), param.getPageSize()), wrapper);
        return PageResult.success(page, Clue.class);
    }

    @PostMapping("/clue/importData")
    @ApiOperation("线索导入")
    public ResponseResult importData(@RequestPart("file") MultipartFile file) throws IOException {
        List<ClueData> clueData = FileUtil.readExcel(file.getInputStream(), ClueData.class);
        List<Clue> clues = BeanUtil.copyToList(clueData, Clue.class);
        clues.forEach(clue -> {
            clue.setOwner(UserContext.getUser());
            clue.setCreateBy(UserContext.getUser());
            clue.setAssignBy(UserContext.getUser());
            clue.setCreateTime(LocalDateTime.now());
        });
        clueService.saveBatch(clues);
        return ResponseResult.success(clues.size());
    }
}
